import mediasoup from 'mediasoup';

export class MediaManager {
  constructor(config) {
    this.config = config;
    this.worker = null;
    this.router = null;
    this.producers = new Map();
    this.consumers = new Map();
  }

  async initialize() {
    try {
      console.log('Initializing MediaManager...');
      
      // 创建 mediasoup Worker
      await this.createWorker();
      
      // 创建 Router
      await this.createRouter();
      
      console.log('MediaManager initialized successfully');
      return true;
      
    } catch (error) {
      console.error('Failed to initialize MediaManager:', error);
      throw error;
    }
  }

  async createWorker() {
    console.log('Creating mediasoup Worker...');
    
    this.worker = await mediasoup.createWorker({
      rtcMinPort: this.config.worker.rtcMinPort,
      rtcMaxPort: this.config.worker.rtcMaxPort,
      logLevel: this.config.worker.logLevel,
      logTags: this.config.worker.logTags
    });

    this.worker.on('died', (error) => {
      console.error('mediasoup Worker died:', error);
      process.exit(1);
    });

    console.log(`Worker created with PID: ${this.worker.pid}`);
  }

  async createRouter() {
    console.log('Creating mediasoup Router...');
    
    this.router = await this.worker.createRouter({
      mediaCodecs: this.config.router.mediaCodecs
    });

    console.log(`Router created with ID: ${this.router.id}`);
  }

  async createWebRtcTransport(options = {}) {
    console.log('Creating WebRTC Transport...');
    
    const transport = await this.router.createWebRtcTransport({
      ...this.config.webRtcTransport,
      ...options
    });

    transport.on('dtlsstatechange', (dtlsState) => {
      console.log(`WebRTC Transport ${transport.id} DTLS state: ${dtlsState}`);
    });

    transport.on('close', () => {
      console.log(`WebRTC Transport ${transport.id} closed`);
    });

    console.log(`WebRTC Transport created: ${transport.id}`);
    return transport;
  }

  async createPlainTransport(options = {}) {
    console.log('Creating Plain Transport...');
    
    const transport = await this.router.createPlainTransport({
      ...this.config.plainTransport,
      ...options
    });

    transport.on('tuple', (tuple) => {
      console.log(`Plain Transport ${transport.id} tuple:`, tuple);
    });

    transport.on('close', () => {
      console.log(`Plain Transport ${transport.id} closed`);
    });

    console.log(`Plain Transport created: ${transport.id}`);
    return transport;
  }

  async createProducer(transport, options) {
    console.log('Creating Producer...');
    
    const producer = await transport.produce(options);

    // 存储 producer
    this.producers.set(producer.id, producer);

    producer.on('score', (score) => {
      console.log(`Producer ${producer.id} score:`, score);
    });

    producer.on('videoorientationchange', (videoOrientation) => {
      console.log(`Producer ${producer.id} video orientation:`, videoOrientation);
    });

    producer.on('close', () => {
      console.log(`Producer ${producer.id} closed`);
      this.producers.delete(producer.id);
    });

    console.log(`Producer created: ${producer.id} (${producer.kind})`);
    return producer;
  }

  async createConsumer(transport, producerId, rtpCapabilities, options = {}) {
    console.log(`Creating Consumer for Producer: ${producerId}`);
    
    // 检查是否可以消费
    if (!this.router.canConsume({ producerId, rtpCapabilities })) {
      throw new Error('Cannot consume this producer');
    }

    const consumer = await transport.consume({
      producerId,
      rtpCapabilities,
      paused: true, // 初始暂停
      ...options
    });

    // 存储 consumer
    this.consumers.set(consumer.id, consumer);

    consumer.on('score', (score) => {
      console.log(`Consumer ${consumer.id} score:`, score);
    });

    consumer.on('layerschange', (layers) => {
      console.log(`Consumer ${consumer.id} layers:`, layers);
    });

    consumer.on('close', () => {
      console.log(`Consumer ${consumer.id} closed`);
      this.consumers.delete(consumer.id);
    });

    consumer.on('producerclose', () => {
      console.log(`Consumer ${consumer.id} producer closed`);
      this.consumers.delete(consumer.id);
    });

    console.log(`Consumer created: ${consumer.id} (${consumer.kind})`);
    return consumer;
  }

  // 创建用于接收 RTSP 流的 Producer
  async createRtspProducer(transport, kind, codecOptions) {
    console.log(`Creating RTSP ${kind} Producer...`);
    
    let rtpParameters;
    
    if (kind === 'video') {
      rtpParameters = {
        codecs: [
          {
            mimeType: codecOptions.mimeType || 'video/VP8',
            clockRate: codecOptions.clockRate || 90000,
            payloadType: codecOptions.payloadType || 96,
            parameters: codecOptions.parameters || {}
          }
        ],
        encodings: [
          {
            ssrc: codecOptions.ssrc || Math.floor(Math.random() * 100000000)
          }
        ]
      };
    } else if (kind === 'audio') {
      rtpParameters = {
        codecs: [
          {
            mimeType: codecOptions.mimeType || 'audio/opus',
            clockRate: codecOptions.clockRate || 48000,
            payloadType: codecOptions.payloadType || 97,
            channels: codecOptions.channels || 2,
            parameters: codecOptions.parameters || {}
          }
        ],
        encodings: [
          {
            ssrc: codecOptions.ssrc || Math.floor(Math.random() * 100000000)
          }
        ]
      };
    }

    const producer = await this.createProducer(transport, {
      kind,
      rtpParameters
    });

    return producer;
  }

  // 获取 Router RTP Capabilities
  getRouterRtpCapabilities() {
    return this.router.rtpCapabilities;
  }

  // 获取所有活跃的 Producers
  getProducers() {
    return Array.from(this.producers.values());
  }

  // 获取所有活跃的 Consumers
  getConsumers() {
    return Array.from(this.consumers.values());
  }

  // 根据 ID 获取 Producer
  getProducer(producerId) {
    return this.producers.get(producerId);
  }

  // 根据 ID 获取 Consumer
  getConsumer(consumerId) {
    return this.consumers.get(consumerId);
  }

  // 获取 Router
  getRouter() {
    return this.router;
  }

  // 获取 Worker
  getWorker() {
    return this.worker;
  }

  // 清理资源
  async cleanup() {
    console.log('Cleaning up MediaManager...');
    
    // 关闭所有 consumers
    for (const consumer of this.consumers.values()) {
      consumer.close();
    }
    this.consumers.clear();

    // 关闭所有 producers
    for (const producer of this.producers.values()) {
      producer.close();
    }
    this.producers.clear();

    // 关闭 router
    if (this.router) {
      this.router.close();
      this.router = null;
    }

    // 关闭 worker
    if (this.worker) {
      this.worker.close();
      this.worker = null;
    }

    console.log('MediaManager cleanup completed');
  }

  // 获取统计信息
  async getStats() {
    const stats = {
      worker: {
        pid: this.worker?.pid,
        died: this.worker?.closed
      },
      router: {
        id: this.router?.id,
        rtpCapabilities: this.router?.rtpCapabilities
      },
      producers: this.producers.size,
      consumers: this.consumers.size
    };

    return stats;
  }
}
